;;; lisp/cli/make.el --- file generation commands -*- lexical-binding: t; -*-
;;; Commentary:
;;; Code:

(load! "make/completions")
;; (load! "make/docs")
;; (load! "make/manpage")


;;
;;; Variables

(defvar doom-make-codeowners-file ".github/CODEOWNERS"
  "Where to write the CODEOWNERS file, relative to the repo's toplevel.")

(defvar doom-make-codeowners ()
  "An alist of codeowners for this project.

Each entry can either be a string (inserted verbatim, surrounded by newlines) or
a pair of strings (in a cons cell) consisting of: (GLOB . CODEOWNERS).

The contents of this variable are inserted in reverse.")


;;
;;; Commands

(defcli! make ()
  "(Re)Generate project files and boilerplate."
  :partial t)

(defcli! (make codeowners)
    ((outfile  ("-o" "--file" (file stdout)) "Where to write the codeowners file")
     (dryrun?  ("--dryrun")))
  "Generate (or update) a CODEOWNERS file.

By default, this means $GIT_WORK_TREE/.github/CODEOWNERS. This will throw an
error if not run in a Git repo.

OPTIONS:
  -o, --file
    Pass this option a dash to print the codeowners file to stdout."
  (when dryrun?
    (setq outfile "-")
    (print! (warn "Running dry run; will only print to stdout:")))
  (with-temp-buffer
    (let ((codeowners-file
           (cond ((equal outfile "-") nil)
                 (outfile (expand-file-name outfile))
                 ((file-name-concat (doom-git-toplevel) doom-make-codeowners-file)))))
      (insert "# -*- mode: conf -*-\n"
              "# Each line is a file pattern followed by one or more owners.\n"
              "# This file was generated by 'doom make codeowners', do not edit it by hand.\n")
      (dolist (entry (nreverse doom-make-codeowners))
        (if (stringp entry)
            (insert "\n" entry "\n")
          (insert (format "%-35s %s" (car entry) (cdr entry)) "\n")))
      (insert "\n# End of CODEOWNERS")
      (setq indent-tabs-mode nil) ; align w/ spaces, not tabs
      (align-regexp (point-min) (point-max) "/\\(\\s-+\\)@" 1)
      (if (null codeowners-file)
          (print! "%s" (buffer-string))
        (print! (start "%s codeowners file at: %s")
                (if (file-exists-p codeowners-file)
                    "Regenerated"
                  "Generated")
                (relpath codeowners-file))
        (write-region (buffer-string) nil codeowners-file)))))

;; TODO Finish me
(defcli-stub! (make changelog))



;;
;;; Helpers

(defmacro doom-make--with-file (file &rest body)
  (declare (indent 1))
  `(let ((inhibit-read-only t))
     (with-current-buffer
         (or (get-file-buffer ,file)
             (find-file-noselect ,file))
       (save-excursion
         (goto-char (point-min))
         ,@body
         (when (buffer-modified-p)
           (save-buffer))))))

(provide 'doom-cli-make)
;;; make.el ends here
